// pages/checkInCalendar/checkInCalendar.js
import { server } from '../../config/server';
import { focuscard } from '../../server/focuscard';

const dateTool = require('../../utils/dateTool');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        server_addr: "",
        all_duration: 0,       // 总专注时长(小时)
        all_duration_int: 0,   // 总专注时长(整数小时)
        avg_duration: 0,       // 日均专注(分钟)
        consecutive_days: 0,   // 连续打卡(天)
        rankList: [],          // 专注排行榜
        my_rank: 0,            // 我的名次
        checkin_trend: []      // 最近7天的打卡信息
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 加载服务器地址
        this.setData({
            server_addr: server.server_addr
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getCheckinStatistics();
        this.getCheckinRanking();
        this.getCheckinTrend();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /*
     * 返回上一页
     */
    returnMainPage() {
        wx.navigateBack({ delta: 1 });
    },

    /*
     * 获取统计数据接口
     */
    getCheckinStatistics() {
        // 调用后端接口
        focuscard.checkinStatistics().then((res) => {
            let int_all_duration = parseInt(res.data.all_duration) || 0;
            this.setData({
                all_duration: (int_all_duration / 60).toFixed(1) || 0,          // 总专注时长(小时)
                all_duration_int: parseInt(int_all_duration / 60) || 0,
                all_duration_min: parseInt(int_all_duration % 60) || 0,
                avg_duration: res.data.avg_duration || 0,          // 日均专注(分钟)
                consecutive_days: res.data.consecutiveDays || 0,   // 连续打卡(天)
            });
        }).catch((err) => {
            console.log(err);
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    },

    getCheckinRanking() {
        // 调用后端接口
        focuscard.checkinRanking().then((res) => {
            let uid = wx.getStorageSync('uid');
            let my_rank = this.data.my_rank;
            let rankList = [];
            console.log(res);
            let r_list = res.data;
            let i;
            let flag = true;
            for (i = 0; i < 5 && i < r_list.length; i++) {
                let item = r_list[i];
                let tmp = {
                    userAvatar: "",
                    username: item.username,
                    durationH: parseInt(item.total_duration / 60),
                    durationM: item.total_duration % 60,
                    days: item.consecutiveDays || 0
                };
                rankList.push(tmp);
                if (r_list[i].uid == uid) {
                    my_rank = i + 1;
                    flag = false;
                }
            }
            // 获取自己的排名
            if (flag) for (; i < r_list.length; i++) {
                if (r_list[i].uid == uid) {
                    my_rank = i + 1;
                    break;
                }
            }
            this.setData({
                my_rank, rankList
            });
        }).catch((err) => {
            console.log(err);
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    },
    getCheckinTrend() {
        // 调用后端接口
        focuscard.checkinTrend().then((res) => {
            let checkin_trend = [];
            let tmp = 1000 * 60 * 60 * 24;
            let date = new Date().getTime();
            date -= tmp * 6;
            let max_duration = 0;
            for (let i = 0; i < 7; i++) {
                let t = new Date(date + i * (tmp));
                let t_format = dateTool.formatDate(t);
                let t_md = t_format.split('-');
                t_md = `${t_md[1]}-${t_md[2]}`;
                let flag = true;
                for (let j in res.data) {
                    j = res.data[j];
                    if (t_format == j.checkin_date) {
                        flag = false;
                        checkin_trend.push({
                            day: t_md,
                            duration: j.total_duration
                        });
                        if (j.total_duration > max_duration) {
                            max_duration = j.total_duration;
                        }
                    }
                }
                if (flag) {
                    checkin_trend.push({
                        day: t_md,
                        duration: 0
                    });
                }
            }
            for (let i = 0; i < checkin_trend.length; i++) {
                let duration = checkin_trend[i].duration;
                let new_duration = max_duration == 0 ? 1 : ((duration / max_duration) * 0.98 + 0.01) * 100;
                checkin_trend[i].duration = new_duration;
            }
            this.setData({ checkin_trend });
        }).catch((err) => {
            console.log(err);
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    }
})